package com.fast.fastenjoy.base.utils;

import java.util.Collection;

import org.apache.commons.beanutils.BeanUtilsBean;
import org.apache.commons.beanutils.Converter;

public class ConvertValueUtil {

	public static Object convert(Object value, Class<?> targetType) {
		Class<?> sourceType = (value == null) ? null : value.getClass();
		Object converted = value;
		Converter converter = lookup(sourceType, targetType);
		if (converter != null) {
			converted = converter.convert(targetType, value);
		}
		if ((targetType == String.class) && (converted != null)
				&& (!(converted instanceof String))) {
			converter = lookup(String.class);
			if (converter != null) {
				converted = converter.convert(String.class, converted);
			}
			if ((converted != null) && (!(converted instanceof String))) {
				converted = converted.toString();
			}
		}

		return converted;
	}

	public static Converter lookup(Class<?> clazz) {
		return BeanUtilsBean.getInstance().getConvertUtils().lookup(clazz);
	}

	public static Converter lookup(Class<?> sourceType, Class<?> targetType) {
		if (targetType == null) {
			throw new IllegalArgumentException("Target type is missing");
		}
		if (sourceType == null) {
			return lookup(targetType);
		}
		Converter converter = null;

		if (targetType == String.class) {
			converter = lookup(sourceType);
			if ((converter == null)
					&& (((sourceType.isArray()) || (Collection.class
							.isAssignableFrom(sourceType))))) {
				converter = lookup(String.class);
			}
			if (converter == null) {
				converter = lookup(String.class);
			}
			return converter;
		}

		if (targetType == String.class) {
			if ((sourceType.isArray())
					|| (Collection.class.isAssignableFrom(sourceType))) {
				converter = lookup(sourceType);
			}
			if (converter == null) {
				converter = lookup(String.class);
			}
			return converter;
		}

		return lookup(targetType);
	}
}
